<?php

namespace App\Repositories\Finance;

use App\Models\PayLog;
use App\Models\Finance\Check;
use App\Repositories\BaseRepository;

class CheckRepository extends BaseRepository
{
    public function __construct(Check $model)
    {
        $this->model = $model;
    }

    //获取所有游戏 各个渠道的 收入
    public function getChannelTotalAmounts($request)
    {
        $matchCondition = [
            'pay_time' => [
                '$gte' => $request['start_time'] . ' 00:00:00',
                '$lte' => $request['end_time'] . ' 23:59:59'
            ],
        ];

        if (!empty($request->game_id)) {
            $matchCondition['game_id'] = [
                '$eq' => $request->game_id
            ];
        }

        if (!empty($request->channel_id)) {
            $matchCondition['channel_id'] = [
                '$eq' => $request->channel_id
            ];
        }

        $query = [
            [
                '$match' => $matchCondition
            ],
            ['$group' =>
                [
                    '_id' => [
                        'game_id' => '$game_id',
                        'channel_id' => '$channel_id',
                    ],
                    'total_amounts' => [
                        '$sum' => [
                            '$toDouble' => '$amounts'
                        ]
                    ],
                ]
            ],
            [
                '$project' => [
                    'key' => [
                        '$concat' => ['$_id.game_id', '-', '$_id.channel_id']
                    ],
                    'game_id' => '$_id.game_id',
                    'channel_id' => '$_id.channel_id',
                    'total_amounts' => 1,
                ]
            ],
            [
                '$sort' => [
                    'game_id' => 1,
                    'channel_id' => 1,
                ]
            ]
        ];


        $collection = PayLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        return $collection;
    }

    public function getCheckList($condition)
    {
        $query = Check::query();
        if (isset($condition['game_id']) && !empty($condition['game_id'])) {
            $query->where('game_id', $condition['game_id']);
        }
        if (isset($condition['channel_id']) && !empty($condition['channel_id'])) {
            $query->where('channel_id', $condition['channel_id']);
        }
        if (isset($condition['start_time']) && !empty($condition['start_time'])) {
            $query->where('start_time', '=', $condition['start_time']);
        }
        if (isset($condition['end_time']) && !empty($condition['end_time'])) {
            $query->where('end_time', '=', $condition['end_time']);
        }
        return $query->with('ratios')->orderBy('updated_at', 'DESC')->get()->toArray();
    }
}